package ciicos.check.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.check.entity.CheckItemsEntity;
import ciicos.check.entity.CheckPlanEntity;
import ciicos.check.entity.CheckPlanItemEntity;
import ciicos.check.entity.CheckPlanTimeEntity;
import ciicos.check.mapper.CheckPlanMapper;
import ciicos.check.model.checkplan.CheckPlanForm;
import ciicos.check.model.checkplan.CheckPlanPagination;
import ciicos.check.service.CheckItemsService;
import ciicos.check.service.CheckPlanItemService;
import ciicos.check.service.CheckPlanService;
import ciicos.check.service.CheckPlanTimeService;
import ciicos.equ.entity.EquPointEntity;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.equ.service.EquPointService;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 巡检计划
 * 版本： V3.2.0
 * 版权：
 * 作者： 产研项目租
 * 日期： 2023-08-16
 */
@Service
public class CheckPlanServiceImpl extends ServiceImpl<CheckPlanMapper, CheckPlanEntity> implements CheckPlanService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Autowired
    private CheckPlanItemService checkPlanItemService;

    @Autowired
    private CheckPlanTimeService checkPlanTimeService;

    @Autowired
    private EquPointService equPointService;
    @Override
    public List<CheckPlanEntity> getList(CheckPlanPagination checkPlanPagination) {
        return getTypeList(checkPlanPagination, checkPlanPagination.getDataType());
    }

    @Override
    public List<CheckPlanEntity> getTypeList(CheckPlanPagination checkPlanPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int checkPlanNum = 0;
        QueryWrapper<CheckPlanEntity> checkPlanQueryWrapper = new QueryWrapper<>();
        int checkPlanItemNum = 0;
        QueryWrapper<CheckPlanItemEntity> checkPlanItemQueryWrapper = new QueryWrapper<>();
        int checkPlanTimeNum = 0;
        QueryWrapper<CheckPlanTimeEntity> checkPlanTimeQueryWrapper = new QueryWrapper<>();

//树形，异步父级查询条件
        long checkPlanItemcount = checkPlanItemService.count();
        long checkPlanTimecount = checkPlanTimeService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(checkPlanPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(checkPlanPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int checkPlanNum1 = 0;
            QueryWrapper<CheckPlanEntity> checkPlanSuperWrapper = new QueryWrapper<>();
            checkPlanNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkPlanSuperWrapper, superQueryList, matchLogic, "check_plan")
                    , new CheckPlanEntity(), checkPlanNum1);
            if (checkPlanNum1 > 0) {
                List<String> checkPlanList = this.list(checkPlanSuperWrapper).stream().map(CheckPlanEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(checkPlanList);
                intersectionSuperList.add(checkPlanList);
            }
            int checkPlanItemNum1 = 0;
            QueryWrapper<CheckPlanItemEntity> checkPlanItemSuperWrapper = new QueryWrapper<>();
            checkPlanItemNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkPlanItemSuperWrapper, superQueryList, matchLogic, "check_plan_item")
                    , new CheckPlanItemEntity(), checkPlanItemNum1);
            if (checkPlanItemNum1 > 0 && checkPlanItemcount > 0) {

                List<String> checkPlanItemList = checkPlanItemService.list(checkPlanItemSuperWrapper).stream().map(CheckPlanItemEntity::getParentid).collect(Collectors.toList());
                allSuperList.addAll(checkPlanItemList);
                intersectionSuperList.add(checkPlanItemList);
            }
            int checkPlanTimeNum1 = 0;
            QueryWrapper<CheckPlanTimeEntity> checkPlanTimeSuperWrapper = new QueryWrapper<>();
            checkPlanTimeNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkPlanTimeSuperWrapper, superQueryList, matchLogic, "check_plan_time")
                    , new CheckPlanTimeEntity(), checkPlanTimeNum1);
            if (checkPlanTimeNum1 > 0 && checkPlanTimecount > 0) {

                List<String> checkPlanTimeList = checkPlanTimeService.list(checkPlanTimeSuperWrapper).stream().map(CheckPlanTimeEntity::getParentid).collect(Collectors.toList());
                allSuperList.addAll(checkPlanTimeList);
                intersectionSuperList.add(checkPlanTimeList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = true;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object checkPlanObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanQueryWrapper, checkPlanPagination.getMenuId(), "check_plan"));
                if (ObjectUtil.isEmpty(checkPlanObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanQueryWrapper = (QueryWrapper<CheckPlanEntity>) checkPlanObj;
                    if (checkPlanQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanNum++;
                    }
                }
                Object checkPlanItemObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanItemQueryWrapper, checkPlanPagination.getMenuId(), "check_plan_item"));
                if (ObjectUtil.isEmpty(checkPlanItemObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanItemQueryWrapper = (QueryWrapper<CheckPlanItemEntity>) checkPlanItemObj;
                    if (checkPlanItemQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanItemNum++;
                    }
                }
                Object checkPlanTimeObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanTimeQueryWrapper, checkPlanPagination.getMenuId(), "check_plan_time"));
                if (ObjectUtil.isEmpty(checkPlanTimeObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanTimeQueryWrapper = (QueryWrapper<CheckPlanTimeEntity>) checkPlanTimeObj;
                    if (checkPlanTimeQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanTimeNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object checkPlanObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanQueryWrapper, checkPlanPagination.getMenuId(), "check_plan"));
                if (ObjectUtil.isEmpty(checkPlanObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanQueryWrapper = (QueryWrapper<CheckPlanEntity>) checkPlanObj;
                    if (checkPlanQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanNum++;
                    }
                }


                Object checkPlanItemObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanItemQueryWrapper, checkPlanPagination.getMenuId(), "check_plan_item"));
                if (ObjectUtil.isEmpty(checkPlanItemObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanItemQueryWrapper = (QueryWrapper<CheckPlanItemEntity>) checkPlanItemObj;
                    if (checkPlanItemQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanItemNum++;
                    }
                }


                Object checkPlanTimeObj = authorizeService.getCondition(new AuthorizeConditionModel(checkPlanTimeQueryWrapper, checkPlanPagination.getMenuId(), "check_plan_time"));
                if (ObjectUtil.isEmpty(checkPlanTimeObj)) {
                    return new ArrayList<>();
                } else {
                    checkPlanTimeQueryWrapper = (QueryWrapper<CheckPlanTimeEntity>) checkPlanTimeObj;
                    if (checkPlanTimeQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkPlanTimeNum++;
                    }
                }


            }
        }


        if (isPc) {
            if (ObjectUtil.isNotEmpty(checkPlanPagination.getName())) {
                checkPlanNum++;

                checkPlanQueryWrapper.lambda().like(CheckPlanEntity::getName, checkPlanPagination.getName());

            }

            if (ObjectUtil.isNotEmpty(checkPlanPagination.getCode())) {
                checkPlanNum++;

                checkPlanQueryWrapper.lambda().like(CheckPlanEntity::getCode, checkPlanPagination.getCode());

            }

            if (ObjectUtil.isNotEmpty(checkPlanPagination.getCheckteam())) {
                checkPlanNum++;

                checkPlanQueryWrapper.lambda().like(CheckPlanEntity::getCheckteam, checkPlanPagination.getCheckteam());

            }

        }
        if (!isPc) {
            if (ObjectUtil.isNotEmpty(checkPlanPagination.getName())) {
                checkPlanNum++;

                checkPlanQueryWrapper.lambda().like(CheckPlanEntity::getName, checkPlanPagination.getName());

            }

            if (ObjectUtil.isNotEmpty(checkPlanPagination.getCode())) {
                checkPlanNum++;

                checkPlanQueryWrapper.lambda().like(CheckPlanEntity::getCode, checkPlanPagination.getCode());

            }

        }
        if (checkPlanItemNum > 0) {
            List<String> checkPlanItemIdList = checkPlanItemService.list(checkPlanItemQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getParentid())).map(t -> t.getParentid()).collect(Collectors.toList());
            long count = checkPlanItemService.count();
            if (count > 0) {
                intersectionList.add(checkPlanItemIdList);
            }
            AllIdList.addAll(checkPlanItemIdList);
        }
        total += checkPlanItemNum;
        if (checkPlanTimeNum > 0) {
            List<String> checkPlanTimeIdList = checkPlanTimeService.list(checkPlanTimeQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getParentid())).map(t -> t.getParentid()).collect(Collectors.toList());
            long count = checkPlanTimeService.count();
            if (count > 0) {
                intersectionList.add(checkPlanTimeIdList);
            }
            AllIdList.addAll(checkPlanTimeIdList);
        }
        total += checkPlanTimeNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            checkPlanQueryWrapper.lambda().in(CheckPlanEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            checkPlanQueryWrapper.lambda().and(t -> t.in(CheckPlanEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(checkPlanPagination.getSidx())) {
            checkPlanQueryWrapper.lambda().orderByDesc(CheckPlanEntity::getCreatortime);
        } else {
            try {
                String sidx = checkPlanPagination.getSidx();
                CheckPlanEntity checkPlanEntity = new CheckPlanEntity();
                Field declaredField = checkPlanEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                checkPlanQueryWrapper = "asc".equals(checkPlanPagination.getSort().toLowerCase()) ? checkPlanQueryWrapper.orderByAsc(value) : checkPlanQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<CheckPlanEntity> page = new Page<>(checkPlanPagination.getCurrentPage(), checkPlanPagination.getPageSize());
                IPage<CheckPlanEntity> userIPage = this.page(page, checkPlanQueryWrapper);
                return checkPlanPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<CheckPlanEntity> list = new ArrayList();
                return checkPlanPagination.setData(list, list.size());
            }
        } else {
            return this.list(checkPlanQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public CheckPlanEntity getInfo(String id) {
        QueryWrapper<CheckPlanEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckPlanEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(CheckPlanEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, CheckPlanEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(CheckPlanEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    //子表方法
    @Override
    public List<CheckPlanItemEntity> getCheckPlanItemList(String id, CheckPlanPagination checkPlanPagination) {
        QueryWrapper<CheckPlanItemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = checkPlanItemService.getChild(checkPlanPagination, queryWrapper);
        queryWrapper.lambda().eq(CheckPlanItemEntity::getParentid, id);
        this.wrapperHandle(queryWrapper, checkPlanPagination.getModuleId(), CheckPlanItemEntity.class, "sub", "checkPlanItem");
        return checkPlanItemService.list(queryWrapper);
    }

    @Override
    public List<CheckPlanItemEntity> getCheckPlanItemList(String id) {
        QueryWrapper<CheckPlanItemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckPlanItemEntity::getParentid, id);
        return checkPlanItemService.list(queryWrapper);
    }

    @Override
    public List<CheckPlanTimeEntity> getCheckPlanTimeList(String id, CheckPlanPagination checkPlanPagination) {
        QueryWrapper<CheckPlanTimeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = checkPlanTimeService.getChild(checkPlanPagination, queryWrapper);
        queryWrapper.lambda().eq(CheckPlanTimeEntity::getParentid, id);
        this.wrapperHandle(queryWrapper, checkPlanPagination.getModuleId(), CheckPlanTimeEntity.class, "sub", "checkPlanTime");
        return checkPlanTimeService.list(queryWrapper);
    }

    @Override
    public List<CheckPlanTimeEntity> getCheckPlanTimeList(String id) {
        QueryWrapper<CheckPlanTimeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckPlanTimeEntity::getParentid, id);
        return checkPlanTimeService.list(queryWrapper);
    }

    //列表子表数据方法

    @Override
    public List<CheckPlanEntity> getListByEnable() {
        QueryWrapper<CheckPlanEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckPlanEntity::getEnabledmark, 1);
        return this.list(queryWrapper);
    }

    @Override
    public List<EquPointEntity> findPointByEquId(String equId) {
        return equPointService.list(new LambdaQueryWrapper<EquPointEntity>()
                .eq(EquPointEntity::getEquid, equId));
    }

    @Autowired
    private CheckItemsService assetsChecksService;

    @Override
    public List<CheckItemsEntity> findDescById(String equId) {

        return assetsChecksService.list(new LambdaQueryWrapper<CheckItemsEntity>()
                .eq(CheckItemsEntity::getId, equId));
    }

    @Autowired
    private CheckPlanMapper checkPlanMapper;

    //验证表单唯一字段
    @Override
    public String checkForm(CheckPlanForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getName())) {
            QueryWrapper<CheckPlanEntity> nameWrapper = new QueryWrapper<>();
            nameWrapper.lambda().eq(CheckPlanEntity::getName, form.getName());
            if (isUp) {
                nameWrapper.lambda().ne(CheckPlanEntity::getId, id);
            }
            if ((int) this.count(nameWrapper) > 0) {
                total++;
                countRecover = "名称";
            }
        }
        if (form.getCheckplanitemList() != null) {
        }
        if (form.getCheckplantimeList() != null) {
        }

        return countRecover;
    }


}
